﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Z13qu.Code;
using Z13qu.Data;
using Z13qu.Model;

namespace Z13qu.Service
{
    /// <summary>
    /// 用户信息服务
    /// </summary>
    public class Sys_UserService : ServiceBase<Sys_User>
    {
        /// <summary>
        /// 判断登陆信息是否正确
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public Sys_User CheckLogin(string username, string password)
        {
            Sys_User userInfo = dbcontext.Sys_User.Where(t => t.Account == username && t.IsDelete == false).FirstOrDefault();
            if (userInfo != null)
            {
                if (userInfo.IsEnabled == true)
                {
                    Sys_UserLogonService userLogonService = new Sys_UserLogonService();
                    Sys_UserLogon userLogon = userLogonService.FindEntity(s=>s.UserId==userInfo.Id);
                    string dbPassword = Md5Helper.Create(DESEncrypt.Encrypt(password.ToLower(), userLogon.UserSecretkey).ToLower());
                    if (dbPassword.ToLower() == userLogon.Password)
                    {
                        DateTime lastVisitTime = DateTime.Now;
                        int LogonCount = (userLogon.LogonCount).ToInt() + 1;
                        if (userLogon.LastVisitTime != null)
                        {
                            userLogon.PreviousVisitTime = userLogon.LastVisitTime.ToDate();
                        }
                        userLogon.LastVisitTime = lastVisitTime;
                        userLogon.LogonCount = LogonCount;
                        userLogonService.Update(userLogon);
                        return userInfo;
                    }
                    else
                    {
                        throw new Exception("密码不正确，请重新输入");
                    }
                }
                else
                {
                    throw new Exception("账户被系统锁定,请联系管理员");
                }
            }
            else
            {
                throw new Exception("账户不存在，请重新输入");
            }
        }
    }
}
